package edu.scdx.controller;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.scdx.common.util.JsonUtil;
import edu.scdx.entity.Cart;
import edu.scdx.entity.Goods;
import edu.scdx.entity.UserInfo;
import edu.scdx.service.CartService;
import edu.scdx.service.GoodsService;
import edu.scdx.service.UserInfoService;
import edu.scdx.service.UserService;

@Controller
@RequestMapping("/cart")
public class CartController {
	
	@Autowired
	 private CartService cartService;
	
	@Autowired
	 private GoodsService goodsService;

	public CartService getCartService() {
		return cartService;
	}

	public void setCartService(CartService cartService) {
		this.cartService = cartService;
	}
	
	@RequestMapping("/addCart.do")
    public String addCart(Model model,HttpSession session){	
		
		int id=(int) session.getAttribute("id");
		
		String userTel=(String) session.getAttribute("userTel");
		
		Goods good=goodsService.getGoodById(id);
		
		String name=good.getName();
		
		String type=good.getType();
		
		String author=good.getAuthor();
		
		String publisher=good.getPublisher();
		
		String description=good.getDescription();
		
		double price=good.getPrice();
		
		double kou=good.getKou();
		
		Cart cart=cartService.getCart(userTel,id);
		
		int number=1;
		
		if(cart==null){
			cartService.addCart(userTel,id,number,name,type,author,publisher,description,price,kou);
		}
		else {
			cartService.updateCart(userTel,id);
		}
		
    	return "addCartOk";
    }
	
	public GoodsService getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	@RequestMapping("/seeCart.do")
    public String getCart(Model model,HttpSession session){	
		
		String userTel=(String) session.getAttribute("userTel");
		
		List<Cart> carts = cartService.getAll(userTel);
		
		model.addAttribute("carts",carts);
		
		return "seeCart";
		
    }
	
	@RequestMapping("/deleteCart.do")
    public String deleteCart(Model model,HttpSession session,String tel,Integer id){	
		
		Cart cart=cartService.getCartNumber(tel,id);
		
		if(cart.getNumber()==1){
			cartService.deleteCart(tel,id);
		}
		
		else {
			cartService.updateCartNumber(tel,id);
		}
		
		
		
		return "deleteCart";
		
    }

}
